/**
 * 
 */
package com.kaba.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.kaba.bean.ResponseResult;
import com.kaba.util.MinioTemplate;
import com.kaba.util.RenameFile;
import io.minio.ObjectStat;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author pvz77
 *
 */
@CrossOrigin
@RestController
@RequestMapping("/file")
public class FileManagerService {
	
	private ArrayNode mimeArray;
	
	private String selectMIME (String suffix) {
		return selectMIME("mime.json", suffix);
	}

	private String selectMIME(String fileName, String suffix) {
		InputStream inputStream = FileManagerService.class.getClassLoader().getResourceAsStream(fileName);
		JsonNode jsonNode;
		if (this.mimeArray == null || mimeArray.size() < 1) {
			try {
				ObjectMapper mapper = new ObjectMapper();
				jsonNode = mapper.readValue(inputStream, JsonNode.class);
				if (jsonNode.isArray()) {
					mimeArray = mapper.convertValue(jsonNode, ArrayNode.class);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		for (JsonNode mObject : mimeArray) {
			if (mObject.get("suffix").asText().equalsIgnoreCase(suffix)) {
				return mObject.get("mime").asText();
			}
		}
		return "application/octet-stream";
	}
	
	/*
	 * 文件上传
	 */
	@RequestMapping("/upLoadFile")
	public ResponseResult upLoadFile(HttpServletRequest request, HttpSession session) {
		MultipartResolver multipartResolver = new CommonsMultipartResolver(session.getServletContext());
		List<Map<String, Object>> result = new ArrayList<Map<String,Object>>();
		if (multipartResolver.isMultipart(request)) {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			Iterator<String> iter = multipartRequest.getFileNames();
			// 新建一个minio连接对象
			MinioTemplate minioTemplate = new MinioTemplate();
			// 桶名
			String bucketName = "st1905";
			
			while (iter.hasNext()) {
				// 获取所有MultipartFile
				MultipartFile multipartFile = multipartRequest.getFile(iter.next().toString());
				if (multipartFile != null) {
					// 获取文件原本名称
					String fileName = multipartFile.getOriginalFilename();
					// 获取文件前缀
					String prefix = RenameFile.getPrefix(fileName);
					// 获取文件后缀
					String suffix = RenameFile.getSuffix(fileName);
					
					// UUID重命名
					fileName = RenameFile.updateFileName(fileName);
					Map<String, Object> zhxx = (Map<String, Object>) session.getAttribute("data");
					  //Employee employee=(Employee) zhxx.get("employee");
					  String dlr=""; //employee.getUname();
					Map<String, Object> map=new HashMap<String, Object>();
					try {
						// 获取输入流
						InputStream inputStream = multipartFile.getInputStream();
						Long fileSize = ((FileInputStream) inputStream).getChannel().size();
						// 上传至minio服务器
						minioTemplate.putObject(bucketName, fileName, inputStream, fileSize, this.selectMIME(suffix));
						ObjectStat info = minioTemplate.getObjectInfo("st1905", fileName);
						// 关闭输入流
						inputStream.close();
						Date createdTime = info.createdTime();
						// 放置返回信息
						map.put("fileExtension", suffix);
						map.put("fileSize", fileSize);
						map.put("originalFileName", prefix);
						map.put("relativeUrl", fileName);
						map.put("uploader", dlr);
						map.put("uploadTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(createdTime));
						result.add(map);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						//e.printStackTrace();
					}
				}
			}
		}
		return new ResponseResult(10001, "文件上传成功", result);
	}

	/*
	 * 文件删除
	 */
	@RequestMapping("/removeFile")
	public ResponseResult removeFile(String fileName) {
		MinioTemplate fileUtil = new MinioTemplate();
		try {
			fileUtil.removeObject("st1905", fileName);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new ResponseResult(1005, "文件删除成功", null);

	}

	/*
	 * 文件下载
	 */
	@RequestMapping("/downloadFile")
	public void downloadFile(String fileName, String originalFileName, HttpServletResponse response) throws IOException {
		MinioTemplate fileUtil = new MinioTemplate();
		InputStream is = fileUtil.getObject("st1905", fileName);
		byte buf[] = new byte[1024];
		int length = 0;
		response.reset();
		response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(originalFileName, "UTF-8"));
		response.setContentType("application/octet-stream");
		response.setCharacterEncoding("UTF-8");
		OutputStream outputStream = response.getOutputStream();
		// 输出文件
		while ((length = is.read(buf)) > 0) {
			outputStream.write(buf, 0, length);
		}
		// 清空缓冲区
		outputStream.flush();
		// 关闭输出流
		outputStream.close();
	}

	/*
	 * 获取视频
	 */
	@GetMapping("/play")
	public void playVideo (String fileName, HttpServletResponse response) throws IOException {
		fileName ="Vue-cli教程：第18讲，Vant项目-L13 个人中心cell - 西瓜视频.mp4";
		MinioTemplate fileUtil = new MinioTemplate();
		InputStream is = fileUtil.getObject("videos", fileName);
		byte buf[] = new byte[1024];
		int length = 0;
		// 获取文件后缀
		String suffix = RenameFile.getSuffix(fileName);
		response.reset();
		response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
		response.setContentType(this.selectMIME(suffix));
		response.setCharacterEncoding("UTF-8");
		OutputStream outputStream = response.getOutputStream();
		// 输出文件
		while ((length = is.read(buf)) > 0) {
			outputStream.write(buf, 0, length);
		}
		// 清空缓冲区
		outputStream.flush();
		// 关闭输出流
		outputStream.close();
	}
}
